package com.hutou.chuangke.uitl;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;

import com.hutou.chuangke.MainApplication;
import com.hutou.chuangke.activity.LoginActivity;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 通用工具类
 **/
public class ActionUtil {

    public static SharedPreferences mSp;
    public static SharedPreferences.Editor mEditor;

    private ActionUtil() {
    }

    public static SharedPreferences getSharedPreferences() {
        if (mSp == null) {
            mSp = MainApplication.getApp().getSharedPreferences("user", 0);
        }
        return mSp;
    }

    public static SharedPreferences.Editor getEditor() {
        if (mEditor == null) {
            mEditor = getSharedPreferences().edit();
        }
        return mEditor;
    }

    /**
     * 设置有新下载标识
     */
    public static void setNewDownloadFlag() {
        SharedPreferences.Editor editor = getEditor();
        editor.putBoolean("has_new_download", true);
        editor.commit();
    }

    /**
     * 清除新下载标识
     */
    public static void clearNewDownloadFlag() {
        SharedPreferences.Editor editor = getEditor();
        editor.putBoolean("has_new_download", false);
        editor.commit();
    }

    /**
     * 查看是否存在新下载
     */
    public static boolean getNewDownloadFlag() {
        SharedPreferences sp = getSharedPreferences();
        return sp.getBoolean("has_new_download", false);
    }

    /**
     * 跳转Activity，如果不需要带参数Bundle设置为null即可
     *
     * @param context 上下文
     * @param cls     跳转目标Activity
     * @param bundle  参数
     **/
    public static void startActivity(Context context, Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(context, cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        context.startActivity(intent);
    }

    public static void startActivity(Context context, Class cls) {
        if (context != null) {
            context.startActivity(new Intent(context, cls));
        }
    }

    public static void startActivity(Context context, Class cls,
                                     int requestCode) {
        Intent intent;
        intent = new Intent(context, cls);
        ((Activity) context).startActivityForResult(intent, requestCode);
    }

    public static void startActivity(Context context, Class cls,
                                     Bundle bundle, int requestCode) {
        Intent intent;
        intent = new Intent(context, cls);
        if (bundle != null)
            intent.putExtras(bundle);
        ((Activity) context).startActivityForResult(intent, requestCode);
    }

    /**
     * 判断SDCard是否存在
     *
     * @return boolean
     */
    public static boolean isSdCardExist() {
        return Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取SD卡根目录路径
     *
     * @return sdpath
     */
    public static String getSdCardPath() {
        boolean exist = isSdCardExist();
        String sdpath = "";
        if (exist) {
            sdpath = Environment.getExternalStorageDirectory().getAbsolutePath();
        } else {
            sdpath = "SDCard未挂载";
        }
        return sdpath;

    }

    /**
     * 判断网络是否可用
     *
     * @return 网络是否可用
     */
    public static boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) MainApplication.getApp()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
        } else {
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 获取版本号
     *
     * @return app版本号
     */
    public static String getAppVersion() {
        String version = "";
        ApplicationInfo appInfo = MainApplication.getApp().getApplicationInfo();
        try {
            PackageInfo pinfo =
                    MainApplication.getApp().getPackageManager().getPackageInfo(appInfo.packageName,
                            PackageManager.GET_CONFIGURATIONS);
            version = pinfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

//    /**
//     * 格式化时间
//     *
//     * @param seconds 时间
//     * @return 格式化后显示的时间
//     */
//    public static String getTime(long milliseconds) {
//        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
//        formatter.setTimeZone(TimeZone.getTimeZone("GMT+0:00"));
//        return formatter.format(seconds * 1000);
//    }

    /**
     * 检测是否已登录并跳转登录
     *
     * @return 是否已登录
     */
    public static boolean checkLoginAndJump() {
        if (TextUtils.isEmpty(MainApplication.getApp().getUid())) {
            startActivity(MainApplication.getContext(), LoginActivity.class, null);
            return false;
        } else {
            return true;
        }
    }

    /**
     * 检测是否已登录
     *
     * @return 是否已登录
     */
    public static boolean checkLogin() {
        if (TextUtils.isEmpty(MainApplication.getApp().getUid())) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取缓存文件大小
     *
     * @return 缓存文件大小
     */
    public static long getCacheFileSize() {
        File picCache = ImageLoader.getInstance().getDiskCache().getDirectory();
        File recordCache = new File(Environment.getExternalStorageDirectory().getPath(), Constant.AUDIO_RECORDER_FOLDER);
        try {
            return FileUtil.getDirFileSize(picCache) + FileUtil.getDirFileSize(recordCache);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 清除缓存
     */
    public static void clearFileCache() {
        File recordCache = new File(Environment.getExternalStorageDirectory().getPath(), Constant.AUDIO_RECORDER_FOLDER);
        FileUtil.delete(recordCache);
        ImageLoader.getInstance().clearDiskCache();
    }


    public static String encodeContent(String content) {
        try {
            return URLEncoder.encode(content, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String decodeContent(String content) {
        try {
            return URLDecoder.decode(content, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 格式化播放时间
     *
     * @param seconds 播放秒数
     * @return 格式化后显示的时间
     */
    public static String getFormatPlayTime(int seconds) {
        StringBuilder sb = new StringBuilder();
        int minutes = seconds / 60;
        if (minutes < 10) {
            sb.append("0");
        }
        sb.append(minutes);
        sb.append(":");
        int secondsOnly = seconds - 60 * minutes;
        if (secondsOnly < 10) {
            sb.append("0");
        }
        sb.append(secondsOnly);
        return sb.toString();
    }

    /**
     * 将毫秒数转换为时间格式
     *
     * @param millisecond 毫秒
     * @return 时间
     */
    public static String progresstime(long millisecond) {
        Date date = new Date(millisecond);
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        return format.format(date);
    }

    /**
     * 将毫秒数转换为时间格式
     *
     * @param millisecond 毫秒
     * @return 时间
     */
    public static String userCenterTime(long millisecond) {
        Date date = new Date(millisecond);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    /**
     * 将毫秒数转换为时间格式
     *
     * @param millisecond 毫秒
     * @return 时间
     */
    public static String dynamicTime(long millisecond) {
        Date date = new Date(millisecond);
        SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
        return format.format(date);
    }

    /**
     * 将毫秒数转换为时间格式
     *
     * @param millisecond 毫秒
     * @return 时间
     */
    public static String fullTime(long millisecond) {
        Date date = new Date(millisecond);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    /**
     * 将毫秒数转换为时间格式
     *
     * @param millisecond 毫秒
     * @return 时间
     */
    public static String messageTime(long millisecond) {
        Date date = new Date(millisecond);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }

    private static final long ONE_MINUTE = 60000L;
    private static final long ONE_HOUR = 3600000L;
    private static final long ONE_DAY = 86400000L;
    private static final long ONE_WEEK = 604800000L;

    private static final String ONE_SECOND_AGO = "秒前";
    private static final String ONE_MINUTE_AGO = "分钟前";
    private static final String ONE_HOUR_AGO = "小时前";
    private static final String ONE_DAY_AGO = "天前";
    private static final String ONE_MONTH_AGO = "月前";
    private static final String ONE_YEAR_AGO = "年前";

    /**
     * 毫秒转换为时间，显示x秒前
     *
     * @param milliseconds 毫秒数
     * @return 格式化后显示的时间
     */
    public static String getFormatTime(long milliseconds) {
        if (milliseconds < 0) {
            return "";
        }

        if (milliseconds < ONE_MINUTE) {
            long seconds = toSeconds(milliseconds);
            return (seconds <= 0 ? 1 : seconds) + ONE_SECOND_AGO;
        }
        if (milliseconds < 45L * ONE_MINUTE) {
            long minutes = toMinutes(milliseconds);
            return (minutes <= 0 ? 1 : minutes) + ONE_MINUTE_AGO;
        }
        if (milliseconds < 24L * ONE_HOUR) {
            long hours = toHours(milliseconds);
            return (hours <= 0 ? 1 : hours) + ONE_HOUR_AGO;
        }
        if (milliseconds < 48L * ONE_HOUR) {
            return "昨天";
        }
        if (milliseconds < 30L * ONE_DAY) {
            long days = toDays(milliseconds);
            return (days <= 0 ? 1 : days) + ONE_DAY_AGO;
        }
        if (milliseconds < 12L * 4L * ONE_WEEK) {
            long months = toMonths(milliseconds);
            return (months <= 0 ? 1 : months) + ONE_MONTH_AGO;
        } else {
            long years = toYears(milliseconds);
            return (years <= 0 ? 1 : years) + ONE_YEAR_AGO;
        }
    }

    private static long toSeconds(long date) {
        return date / 1000L;
    }

    private static long toMinutes(long date) {
        return toSeconds(date) / 60L;
    }

    private static long toHours(long date) {
        return toMinutes(date) / 60L;
    }

    private static long toDays(long date) {
        return toHours(date) / 24L;
    }

    private static long toMonths(long date) {
        return toDays(date) / 30L;
    }

    private static long toYears(long date) {
        return toMonths(date) / 365L;
    }
}
